package com.c2rusthub.service.service;

import com.c2rusthub.service.controller.BaseController;
import com.c2rusthub.service.mapper.UserMapper;
import com.c2rusthub.service.model.User;
import com.c2rusthub.service.utils.UserCacheUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class UserService extends BaseController {

    @Autowired
    private UserMapper userMapper;

    public List<User> getAllUsers() {
        return userMapper.findAll();
    }

    /**
     * 用户登录验证
     *
     * @param account  用户的账号
     * @param password 用户的密码
     * @return 用户信息，验证通过则返回 User 对象，否则返回 null
     */
    public User logIn(String account, String password) {
        // 查询数据库中的用户信息
        User user = userMapper.selectByAccount(account);

        // 验证密码是否匹配
        if (user != null && user.getPassword().equals(DigestUtils.md5Hex(password))) {
            // 登录成功，将 token 存入缓存，设置过期时间
            String token = UUID.randomUUID().toString();
            user.setToken(token);
            UserCacheUtil.putUserToCache(token, user);
//            cacheService.putToCache(token, user);
            user.setPassword("");
            return user;
        }

        return null; // 如果没有匹配的用户或密码错误
    }

    public void logOut(String token) {
        UserCacheUtil.removeUserFromCache(token);
    }


}
